package com.itheima.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.PermissionMapper;
import com.itheima.dao.RoleMapper;
import com.itheima.dao.UserMapper;
import com.itheima.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    PermissionMapper permissionMapper;
    @Autowired
    RoleMapper roleMapper;
    @Override
    public User findUserByUserName(String username) {
       return userMapper.findUserByUserName(username);
    }

    @Override
    public List<String> getAuthorityByUserId(Integer id) {
        return permissionMapper.getAuthorityByUserId(id);

    }


    @Override
    public PageResult findAll(QueryPageBean queryPageBean) {
        //告诉mybatis要分页
      Page page=  PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
         userMapper.findPage(queryPageBean.getQueryString());

        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void add(User user) {

        userMapper.add(user);
        Integer userId = user.getId();
        List<Integer> roleIds = user.getRoleIds();
        String password = user.getPassword();
        BCryptPasswordEncoder bc = new BCryptPasswordEncoder();
        String encode = bc.encode(password);
        user.setPassword(encode);
            setUserAndRole(userId,roleIds);




        /*if (CollectionUtil.isNotEmpty(roleIds)){
            for (Integer roleId : roleIds) {
                Map map =new HashMap();
                map.put("userId",userId);
                map.put("roleId",roleId);
                userMapper.setUserAndRole(map);
            }

         }*/
    }

    public void setUserAndRole(Integer userId,List<Integer>roleIds){
        //循环建立检查组和检查项的关系
        if (CollectionUtil.isNotEmpty(roleIds)) {
            List<Map> params =new ArrayList<>();
            for (Integer roleId : roleIds) {
                Map map = new HashMap();
                map.put("userId",userId);
                map.put("roleId",roleId);
                params.add(map);
            }
            userMapper.setUserAndRole(params);
        }
    }

    @Override
    public Set<Role> findAllRole() {

        return  userMapper.findAllRole();
    }

    @Override
    public UserEditVo findUserById(Integer id) {
       //根据id查询用户基本信息
       User user= userMapper.findById(id);
        //查询所有的角色信息
       Set<Role> roles= userMapper.findAllRole();
        //根据上次勾选的角色id集合
       List<Integer> ids =userMapper.findRoleIdsByUserId(id);

        UserEditVo vo =new UserEditVo();
        vo.setUser(user);
        vo.setRoles(roles);
        vo.setRoleIds(ids);
        return vo;
    }

    @Override
    public void edit(User user) {
        Integer userId = user.getId();
        List<Integer> roleIds = user.getRoleIds();
        //更新用户信息
        String password = user.getPassword();
        BCryptPasswordEncoder bc = new BCryptPasswordEncoder();
        String encode = bc.encode(password);
        user.setPassword(encode);

        userMapper.edit(user);
        //删除原来的关系
        userMapper.deleteRelation(userId);
        //建立新的关系
         setUserAndRole(userId,roleIds);
    }

    @Override
    public void delete(Integer id) {
        Integer count= userMapper.findUserById(id);
        if (count>0){
            throw new RuntimeException("存在引用，不能删除");
        }else {
            userMapper.delete(id);
        }
    }


}
